package com.scs.application.modules.fsd.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.fsd.entity.FsdChestUser;
import com.scs.application.modules.fsd.mapper.ChestUserMapper;
import com.scs.application.modules.fsd.service.ChestUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 */
@Service
public class ChestUserServiceImpl extends BaseServiceImpl<ChestUserMapper, FsdChestUser> implements ChestUserService {

    @Override
    public List<FsdChestUser> getUsersByChest(String id) {
        return baseMapper.getUsersByChest(id);
//        return this.list(Wrappers.<FsdChestUser>query().eq("chest_id",id));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changeUsersByChest(String userIds, String chestId) {
        remove(Wrappers.<FsdChestUser>query().eq("chest_id",chestId));
        Collection<FsdChestUser> chestUsers = new ArrayList<>();
        String[] userIdArray = userIds.split(",");
        for (String user_id : userIdArray){
            if(StringUtils.isBlank(user_id)) continue;
            FsdChestUser chestUser = new FsdChestUser();
            chestUser.setChestId(chestId);
            chestUser.setUserId(user_id);
            chestUsers.add(chestUser);
        }
        saveBatch(chestUsers);
        return true;
    }

    @Override
    public List<Map<String, Object>> getChestsAndStationsByUserId(String id) {
       return baseMapper.getChestsAndStationsByUserId(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changeChestsByUser(String chestIds, String userId) {
        remove(Wrappers.<FsdChestUser>query().eq("user_id",userId));
        Collection<FsdChestUser> chestUsers = new ArrayList<>();
        String[] chestIdArray = chestIds.split(",");
        for (String chest_id : chestIdArray){
            if(StringUtils.isBlank(chest_id)) continue;
            FsdChestUser chestUser = new FsdChestUser();
            chestUser.setChestId(chest_id);
            chestUser.setUserId(userId);
            chestUsers.add(chestUser);
        }
        saveBatch(chestUsers);
        return true;
    }
}
